# -*- coding:utf-8 -*- #

from level import Data, InfoData
import time
from threading import RLock

#引入上层目录模块方法
import sys
sys.path.append("..")
from utils.alarm import writealarminfo
from conf import configure

class Filter(object):
    """docstring for Filter"""
    def __init__(self, id):
        self.id = id

    def filt(self, data):
        pass

    
def now():
    '''获取当前时间'''
    return int(time.time())

class MonitorFilter(Filter):
    """docstring for MonitorFilter"""
    def __init__(self, id):
        #初始化，得到检测的id号
        super(MonitorFilter, self).__init__(id)

    def filt(self, data):
        # data {'硬盘剩余': [2.4, "GB"],'硬盘使用率': [57.0, "%"]}
        if isinstance(data, Data):
            data.update({'id': self.id, 'filter': 'monitor_filter',
                'datetime': now(), 'is_attention': 0, 'type': 3})
            if not isinstance(data, InfoData):
                #如果是报警数据，就升级为1
                data.update({'is_attention': 1})
        else:
            data = None

        return data

"""
alarm_list = {id1: [level, last_time, time_levels_list], id2: [level,
last_time, time_levels]}
"""
alarm_list = {}

class AlarmFilter(Filter):
    """docstring for AlarmFilter"""
    lock = RLock()

    def __init__(self, id):
        super(AlarmFilter, self).__init__(id)

    def filt(self, data):
        self.lock.acquire()
        global alarm_list

        # data {'硬盘剩余': [1.7, "GB"],'硬盘使用率': [71.0, "%"]}
        if not isinstance(data, Data):
            return None

        data.update({'id': self.id, 'filter': 'alarm_filter', 'type':3})
        # data = {"filter": "alarm_filter", 
        #          "type": 3, "硬盘剩余": [1.7, "GB"], "硬盘使用率": [71.0, "%"], "id": 201}
        print "alarm_list3:==",alarm_list
        
        last = alarm_list.get(self.id)
        print "last ===",last

        if isinstance(data, InfoData):
            # 报警数据恢复会正常
            if last is not None:
                alarm_list.pop(self.id)
                data.update({'level': 0, 'end_time': now()})
                ''' data = {"filter": "alarm_filter", 
                        "level": 0, 
                        "type": 3, 
                        "硬盘剩余": [1.7, "GB"],
                        "begin_time": 1333680664, 
                        "硬盘使用率": [71.0, "%"], 
                        "id": 201}
                '''
            else:
                data = None
        else:
            
            
            data.update({'begin_time': now()})
            ''' data = {"filter": "alarm_filter", 
                        "type": 3, 
                        "硬盘剩余": [1.7, "GB"],
                        "begin_time": 1333680664, 
                        "硬盘使用率": [71.0, "%"], 
                        "id": 201}
            '''
            if not last:
                #第一次就检测为预警信息
                import cmdloader
                conf_info = configure.cmdconfig
                object_cmdloader = cmdloader.CmdLoader()
                config = object_cmdloader.load(conf_info)

                for v in object_cmdloader.detail('alarmcfg').values():
                    
                    if v['id'] == self.id:
                        # 获取 后期报警时间间隔 [10, 10, 10, 10]
                        time_levels = list(v['rate'][1])
                        
                        alarm_list[self.id] = [1, now(), time_levels]
                        #加入level = 1
                        data.update({'level': 1})
                        break
            else:
                #last已经有数据,则进行预警级别升级
                data = self.level_up(data)
                
        # 将alarm_list写入文件 {201: [1, 1333681533, [10, 10, 10, 10]]}
        writealarminfo(alarm_list)
        self.lock.release()
        '''
        data = {"filter": "alarm_filter", 
        "硬盘剩余": [1.7, "GB"], 
        "begin_time": 1333681533, 
        "level": 1, 
        "type": 3, 
        "id": 201, 
        "硬盘使用率": [71.0, "%"]}
        '''
        return data

    def level_up(self, data):
        # alarm_list = {201: [1, 1333683432, [10, 10, 10, 10]]}
        global alarm_list
        print "alarm_list old level 1",alarm_list
        
        # level= 1
        level = alarm_list[self.id][0]
        # last = 1333683432
        last = alarm_list[self.id][1]
        # time_levels = [10, 10, 10, 10]
        time_levels = alarm_list[self.id][2]
        

        # for ... else ...用法说明
        # 即在for 循环中，如果没有从任何一个break中退出，则会执行和for对应的else
        # 只要从break中退出了，则else部分不执行。
        
        
        # enumerate 对一个列表既遍历其索引又要遍历其元素
        for n, t in enumerate(time_levels):
            # n是索引 从0开始
            # t是list的值

            if self._timeout(last, t):
                # 第一次报警级别为1，因此time_levels的第一个时间段的报警级别还是1
                if level < (n + 1):
                    # 报警级别
                    alarm_list[self.id][0] = n + 1
                    # 检测时间
                    alarm_list[self.id][1] = now()
                    data.update({'level': n + 1})
                    break
        else:
            # 第二次预警，级别不变，数据清空
            data = None

        return data

    def _timeout(self, last, t):
        return True and now() - last > t

class LoggerFilter(Filter):
    """docstring for LoggerFilter"""
    def __init__(self, id):
        super(LoggerFilter, self).__init__(id)

    def filt(self, data):
        if not isinstance(data, InfoData):
            data.update({'id': self.id, 'filter': 'logger_filter',
                'datetime': now(), 'type': 3})
        else:
            data = None
        return data

